<script lang="ts" setup>
import type { DialogModel, Role, User } from '@/index.d';
import { getById, reSetDialogModel, urls, getReadonly, insertOne, updateOne } from '@/index';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';

const dialogModel = defineModel<DialogModel<Role>>('dialogModel', { required: true });

const { updateForbidden } = getReadonly(dialogModel.value);

const formData = reactive<Role>({ type: '自定义' });

const setData = async (res: Role) => {
  formData.id = res.id;
  formData.name = res.name;
  formData.description = res.description;
  formData.type = res.type;
  formData.creator = res.creator;
  formData.createTime = res.createTime;
  formData.updater = res.updater;
  formData.updateTime = res.updateTime;
};

const reSet = () => {
  reSetDialogModel(dialogModel);
};

watch(
  () => dialogModel.value.id,
  async value => {
    if (value !== 0) {
      try {
        const res = (await getById(urls.role, value)) as Role;
        setData(res);
      } catch (error) {
        ElMessage.error('获取失败，错误信息是：' + error);
      }
    }
  },
  {
    immediate: true
  }
);

// 当对话框关闭时，当窗口打开时，将父元素传递过来的id赋值给user，重置user的数据
watch(
  () => dialogModel.value.visible,
  value => {
    value && (formData.id = dialogModel.value.id as number);
    !value && reSet();
  },
  {
    immediate: true
  }
);

const formRef = ref<FormInstance>();

interface RoleFormRules {
  name: '内置' | '自定义';
  type: string;
}

// 表单校验规则;
const formRules = computed(() => {
  switch (dialogModel.value.type) {
    case 'view':
      return reactive({});

    case 'update':
      return reactive<FormRules<RoleFormRules>>({
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '类型不能为空', trigger: 'blur' }]
      });
    case 'insert':
      return reactive<FormRules<RoleFormRules>>({
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '类型不能为空', trigger: 'blur' }]
      });
  }
});

const saveData = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (valid) {
      if (dialogModel.value.id === 0) {
        const res = (await insertOne(urls.role, formData)) as User;
        if (res) {
          setData(res);
          dialogModel.value.id = res.id as number;
          dialogModel.value.type = 'update';
          dialogModel.value.change = true;
        }
      } else {
        const tempDataForSave: Role = {
          id: formData.id,
          type: formData.type,
          name: formData.name,
          description: formData.description
        };
        const res = (await updateOne(urls.role, tempDataForSave)) as Role;
        if (res) {
          dialogModel.value.change = true;
          formData.updater = res.updater;
          formData.updateTime = res.updateTime;
        }
      }
    }
  });
};
</script>
<template>
  <hq-dialog-detail
    v-model:dialogModel="dialogModel"
    v-if="dialogModel.visible"
    @submit="saveData(formRef)"
    :operation="formData"
  >
    <template #default>
      <el-card shadow="hover">
        <template #header>基本信息</template>
        <template #default>
          <el-form :model="formData" :rules="formRules" ref="formRef" status-icon label-suffix="：">
            <el-row :gutter="5">
              <hq-col v-show="true">
                <el-form-item label="序号" prop="id">
                  <el-input v-model.number="formData.id" readonly />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="类型" prop="type">
                  <el-select v-model="formData.type" placeholder="请选择角色类型" clearable>
                    <el-option label="自定义" value="自定义" />
                    <el-option label="内置" value="内置" />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="名称" prop="name">
                  <el-input v-model.trim="formData.name" :readonly="updateForbidden" />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="描述" prop="description">
                  <el-input v-model.trim="formData.description" />
                </el-form-item>
              </hq-col>
            </el-row>
          </el-form>
        </template>
      </el-card>
    </template>
  </hq-dialog-detail>
</template>
<style lang="scss" scoped></style>
